package com.shushan.pages;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.common.ui.banner.Banner;
import com.android.common.ui.banner.BannerConfig;
import com.android.common.ui.banner.listener.OnBannerListener;
import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.huawei.android.hms.agent.HMSAgent;
import com.huawei.android.hms.agent.pay.PaySignUtil;
import com.huawei.android.hms.agent.pay.handler.PayHandler;
import com.huawei.hms.support.api.entity.pay.PayStatusCodes;
import com.huawei.hms.support.api.pay.PayResultInfo;
import com.shushan.base.Constants;
import com.shushan.base.NavigationLoseActivity;
import com.shushan.home.OpenSectVipActivity;
import com.shushan.home.bean.AppDialogBean;
import com.shushan.home.bean.BannerDataBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.pages.bean.ActivityVipBean;
import com.shushan.pages.bean.OpenVipBean;
import com.shushan.pages.bean.VipBean;
import com.shushan.pages.bean.WXPayBean;
import com.shushan.service.DialRTAService;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.BuildConfig;
import com.shushan.shushanbao.R;
import com.shushan.shushanbao.wxapi.WXPayEntryActivity;
import com.shushan.util.GlideImageLoader;
import com.shushan.util.PayUtils;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.SystemUtils;
import com.shushan.util.ToolUtils;
import com.shushan.util.UmengEventUtil;
import com.shushan.web.AdvertWebActivity;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: OpenVipSpendActivity
 * @Desciption: 开通VIP
 * @author: yichaohua
 * @date: 2018-07-18
 */
public class OpenVipSpendActivity extends NavigationLoseActivity implements View.OnClickListener {

    private static final String TAG = "OpenVipSpendActivity";

    private RelativeLayout radioButton1, radioButton2, radioButton3;
    private RelativeLayout sectVipLayou, extractVipLayout;
    private RelativeLayout superVipLayout;
    private RelativeLayout synchroVipLayout;
    private RelativeLayout strangeVipLayout;
    private RelativeLayout oralVipLayout;
    private RelativeLayout speakingVipLayout;
    private RelativeLayout wordsVipLayout;
    private RelativeLayout hearVipLayout;
    private TextView superEndText;
    private TextView synchroEndText;
    private TextView strangeEndText;
    private TextView oralEndText;
    private TextView speakingEndText;
    private TextView wordsEndText;
    private TextView hearEndText;
    private TextView discountTv1, discountTv2, discountTv3;
    private TextView origTv1, origTv2, origTv3;
    private OpenVipBean openVipBean1, openVipBean2, openVipBean3;
    private OpenVipBean selectVipBean;
    private TextView spendTextView;
    private TextView openTextView;
    private TextView extractText;
    private TextView nameText;
    private TextView dateText;
    private ImageView vipIconImg;
    private ImageView spreadImg;
    private Banner mBanner;

    private BabyApplication babyApplication = BabyApplication.getInstance();
    private List<AppDialogBean> appDialogBeanList;
    private IWXAPI api;
    private int first = 0;
    private int subSectVip = 0;
    private VipBean currentVipBean;
    private ActivityVipBean activityVipBean;
    private boolean isSpread = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.open_vip_activity);

        setTitle("会员中心");

        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        api.registerApp(Constants.APP_ID);

        initViwe();

        //初始化广告栏
        initBanner();

        UmengEventUtil.onEvent(babyApplication, "vip_center_page_id");
    }

    @Override
    protected void onResume() {
        super.onResume();

        getData();
    }

    private void initViwe() {
        extractText = findViewById(R.id.open_vip_extract_tv);
        mBanner = findViewById(R.id.banner);
        superEndText = findViewById(R.id.open_vip_vip_end_tv);
        synchroEndText = findViewById(R.id.open_vip_vip_synchro_end_tv);
        strangeEndText = findViewById(R.id.open_vip_vip_strange_end_tv);
        oralEndText = findViewById(R.id.open_vip_vip_oral_end_tv);
        speakingEndText = findViewById(R.id.open_vip_vip_speaking_end_tv);
        wordsEndText = findViewById(R.id.open_vip_vip_words_end_tv);
        hearEndText = findViewById(R.id.open_vip_vip_hear_end_tv);
        vipIconImg = findViewById(R.id.open_vip_vip_img);
        spreadImg = findViewById(R.id.open_vip_vip_spread_img);
        superVipLayout = findViewById(R.id.open_vip_super_layout);
        superVipLayout.setOnClickListener(this);
        synchroVipLayout = findViewById(R.id.open_vip_synchro_layout);
        strangeVipLayout = findViewById(R.id.open_vip_strange_layout);
        oralVipLayout = findViewById(R.id.open_vip_oral_layout);
        speakingVipLayout = findViewById(R.id.open_vip_speaking_layout);
        wordsVipLayout = findViewById(R.id.open_vip_words_layout);
        hearVipLayout = findViewById(R.id.open_vip_hear_layout);
        nameText = findViewById(R.id.open_vip_name_tv);
        dateText = findViewById(R.id.open_vip_vip_end_tv);
        radioButton1 = findViewById(R.id.open_vip_layout1);
        radioButton1.setOnClickListener(this);
        radioButton2 = findViewById(R.id.open_vip_layout2);
        radioButton2.setOnClickListener(this);
        radioButton3 = findViewById(R.id.open_vip_layout3);
        radioButton3.setOnClickListener(this);
        discountTv1 = findViewById(R.id.open_vip_discount_tv1);
        discountTv2 = findViewById(R.id.open_vip_discount_tv2);
        discountTv3 = findViewById(R.id.open_vip_discount_tv3);
        origTv1 = findViewById(R.id.open_vip_orig_tv1);
        origTv1.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        origTv2 = findViewById(R.id.open_vip_orig_tv2);
        origTv2.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        origTv3 = findViewById(R.id.open_vip_orig_tv3);
        origTv3.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        spendTextView = findViewById(R.id.open_vip_spend_tv);
        openTextView = findViewById(R.id.open_vip_tv);
        openTextView.setOnClickListener(this);
        sectVipLayou = findViewById(R.id.open_vip_sect_layout);
        sectVipLayou.setOnClickListener(this);
        extractVipLayout = findViewById(R.id.open_vip_extract_layout);
        extractVipLayout.setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBanner.stopAutoPlay();
    }

    private void initBanner() {
        mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR).setImageLoader(new GlideImageLoader());
        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                if (!ToolUtils.isListEmpty(appDialogBeanList)) {
                    AppDialogBean appDialogBean = appDialogBeanList.get(position);
                    if (appDialogBean != null) {
                        bannerJump(appDialogBean);
                    }
                }
            }
        });
    }

    private void getData() {
        showWaitDialog();

        int childId = babyApplication.getCurrentChildId();
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.GET_OPEN_VIPS);
        urlParse.putValue("child_id", childId);

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<VipBean>() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(VipBean vipBean) {
                        if (vipBean != null) {
                            currentVipBean = vipBean;
                            first = vipBean.first;
                            if (vipBean.first == 1) {
                                radioButton1.setBackgroundResource(R.drawable.vip_rb_nor_first);
                            }

                            appDialogBeanList = vipBean.getAppDialogBeanList();
                            if (!ToolUtils.isListEmpty(appDialogBeanList)) {
                                setBanner(appDialogBeanList);
                            }

                            List<ActivityVipBean> activityBeanList = vipBean.getActivityBeanList();
                            if (!ToolUtils.isListEmpty(activityBeanList)) {
                                activityVipBean = activityBeanList.get(0);
                                extractText.setText(activityVipBean.name);
                                extractVipLayout.setVisibility(View.VISIBLE);
                            } else {
                                extractVipLayout.setVisibility(View.GONE);
                            }

                            subSectVip = vipBean.tb_vip + vipBean.sz_vip + vipBean.ks_vip + vipBean.ky_vip
                                    + vipBean.dc_vip + vipBean.tl_vip;
                            if (subSectVip > 0) {
                                spreadImg.setVisibility(View.VISIBLE);
                            } else {
                                spreadImg.setVisibility(View.INVISIBLE);
                            }

                            if (subSectVip + vipBean.vip > 0) {
                                superVipLayout.setVisibility(View.VISIBLE);
                                vipIconImg.setVisibility(View.VISIBLE);
                            } else {
                                superVipLayout.setVisibility(View.GONE);
                                vipIconImg.setVisibility(View.GONE);
                            }
                            nameText.setText(vipBean.child_name);

                            if (vipBean.vip == 1) {
                                dateText.setText("超级VIP会员时间还有" + vipBean.last_time + "天");
                            } else if (vipBean.tb_vip == 1) {
                                dateText.setText("同步练习VIP会员时间还有" + vipBean.tb_vip_time + "天");
                            } else if (vipBean.sz_vip == 1) {
                                dateText.setText("生字练习VIP会员时间还有" + vipBean.sz_vip_time + "天");
                            } else if (vipBean.ks_vip == 1) {
                                dateText.setText("口算练习VIP会员时间还有" + vipBean.ks_vip_time + "天");
                            } else if (vipBean.ky_vip == 1) {
                                dateText.setText("口语练习VIP会员时间还有" + vipBean.ky_vip_time + "天");
                            } else if (vipBean.dc_vip == 1) {
                                dateText.setText("单词练习VIP会员时间还有" + vipBean.dc_vip_time + "天");
                            } else if (vipBean.tl_vip == 1) {
                                dateText.setText("听力练习VIP会员时间还有" + vipBean.tl_vip_time + "天");
                            }

                            synchroEndText.setText("同步练习VIP会员时间还有" + vipBean.tb_vip_time + "天");
                            strangeEndText.setText("生字练习VIP会员时间还有" + vipBean.sz_vip_time + "天");
                            oralEndText.setText("口算练习VIP会员时间还有" + vipBean.ks_vip_time + "天");
                            speakingEndText.setText("口语练习VIP会员时间还有" + vipBean.ky_vip_time + "天");
                            wordsEndText.setText("单词练习VIP会员时间还有" + vipBean.dc_vip_time + "天");
                            hearEndText.setText("听力练习VIP会员时间还有" + vipBean.tl_vip_time + "天");

                            List<OpenVipBean> openVipBeanList = vipBean.getOpenVipBeanList();
                            for (int i = 0; i < 3; i++) {
                                if (i == 0) {
                                    openVipBean1 = openVipBeanList.get(i);
                                    discountTv1.setText(openVipBean1.cost_price + "元/月");
                                    origTv1.setText("原价" + openVipBean1.favorable_price);
                                } else if (i == 1) {
                                    openVipBean2 = openVipBeanList.get(i);
                                    discountTv2.setText(openVipBean2.cost_price + "元/3个月");
                                    origTv2.setText("原价" + openVipBean2.favorable_price);
                                } else if (i == 2) {
                                    selectVipBean = openVipBeanList.get(i);
                                    openVipBean3 = openVipBeanList.get(i);
                                    discountTv3.setText(openVipBean3.cost_price + "元/12个月");
                                    origTv3.setText("原价" + openVipBean3.favorable_price);
                                    spendTextView.setText(openVipBean3.cost_price + "元");

                                    if (openVipBean3 != null) {
                                        radioButton1.setBackgroundResource(first == 1 ? R.drawable.vip_rb_nor_first : R.drawable.month_vip_rb_nor);
                                        radioButton2.setBackgroundResource(R.drawable.quarter_vip_rb_nor);
                                        radioButton3.setBackgroundResource(R.drawable.vip_rb_commend_select);
                                    }
                                }
                            }

                        }

                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void setBanner(List<AppDialogBean> appDialogBeanList) {
        if (ToolUtils.isListEmpty(appDialogBeanList)) {
            return;
        }
        List<String> images = new ArrayList<String>();
        for (AppDialogBean bean : appDialogBeanList) {
            images.add(bean.pic);
        }
        mBanner.setImages(images).start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.open_vip_tv:
                if ("oppo".equals(BuildConfig.ENVIRONMENT)) {
                    if (selectVipBean == null) {
                        showToast("活动信息为空");
                        return;
                    }
                    PayUtils.orderOppoSupperPay(this, 0, selectVipBean.vip_time, selectVipBean.cost_price);
                } else if (getPackageName().equals(Constants.MASTER_PACKAGE_NAME)) {
                    orderPay();
                } else {
                    PayUtils.openVipHuawei(this, selectVipBean);
                }
                UmengEventUtil.onEvent(babyApplication, "open_vip_id", selectVipBean.cost_price + "");
                break;
            case R.id.open_vip_layout1:
                if (openVipBean1 != null) {
                    selectVipBean = openVipBean1;
                    radioButton1.setBackgroundResource(first == 1 ? R.drawable.vip_rb_select_first : R.drawable.vip_rb_select);
                    radioButton2.setBackgroundResource(R.drawable.quarter_vip_rb_nor);
                    radioButton3.setBackgroundResource(R.drawable.vip_rb_nor);
                    spendTextView.setText(openVipBean1.cost_price + "元");
                }
                break;
            case R.id.open_vip_layout2:
                if (openVipBean2 != null) {
                    selectVipBean = openVipBean2;
                    radioButton1.setBackgroundResource(first == 1 ? R.drawable.vip_rb_nor_first : R.drawable.month_vip_rb_nor);
                    radioButton2.setBackgroundResource(R.drawable.quarter_vip_rb_select);
                    radioButton3.setBackgroundResource(R.drawable.vip_rb_nor);
                    spendTextView.setText(openVipBean2.cost_price + "元");
                }
                break;
            case R.id.open_vip_layout3:
                if (openVipBean3 != null) {
                    selectVipBean = openVipBean3;
                    radioButton1.setBackgroundResource(first == 1 ? R.drawable.vip_rb_nor_first : R.drawable.month_vip_rb_nor);
                    radioButton2.setBackgroundResource(R.drawable.quarter_vip_rb_nor);
                    radioButton3.setBackgroundResource(R.drawable.vip_rb_commend_select);
                    spendTextView.setText(openVipBean3.cost_price + "元");
                }
                break;
            case R.id.open_vip_sect_layout:
                startActivity(OpenSectVipActivity.class);
                break;
            case R.id.open_vip_extract_layout:
                if (activityVipBean == null) {
                    showToast("提分计划信息为空");
                    break;
                }
                Intent intent2 = new Intent(this, AdvertWebActivity.class);
                intent2.putExtra("title", activityVipBean.name);
                intent2.putExtra("url", activityVipBean.url);
                startActivityAllow(intent2);
                break;
            case R.id.open_vip_super_layout:
                swichVip();
                break;
            default:
                break;
        }
    }

    private void swichVip() {
        Log.i(TAG, "subSectVip=" + subSectVip + " isSpread=" + isSpread);
        if (currentVipBean != null && subSectVip > 0) {
            if (isSpread) {
                synchroVipLayout.setVisibility(View.GONE);
                strangeVipLayout.setVisibility(View.GONE);
                oralVipLayout.setVisibility(View.GONE);
                speakingVipLayout.setVisibility(View.GONE);
                wordsVipLayout.setVisibility(View.GONE);
                hearVipLayout.setVisibility(View.GONE);

                spreadImg.setImageResource(R.drawable.spread_right_icon);
                isSpread = false;
            } else {
                if (currentVipBean.tb_vip == 1) {
                    synchroVipLayout.setVisibility(View.VISIBLE);
                }
                if (currentVipBean.sz_vip == 1) {
                    strangeVipLayout.setVisibility(View.VISIBLE);
                }
                if (currentVipBean.ks_vip == 1) {
                    oralVipLayout.setVisibility(View.VISIBLE);
                }
                if (currentVipBean.ky_vip == 1) {
                    speakingVipLayout.setVisibility(View.VISIBLE);
                }
                if (currentVipBean.dc_vip == 1) {
                    wordsVipLayout.setVisibility(View.VISIBLE);
                }
                if (currentVipBean.tl_vip == 1) {
                    hearVipLayout.setVisibility(View.VISIBLE);
                }

                spreadImg.setImageResource(R.drawable.spread_down_icon);
                isSpread = true;
            }
        }
    }

    private void orderPay() {
        if (api.getWXAppSupportAPI() < Build.PAY_SUPPORTED_SDK_INT) {
            showToast("您未安装最新版本微信，不支持微信支付，请安装或升级微信版本");
            return;
        }

        if (selectVipBean == null) {
            showToast("活动信息为空");
            return;
        }

        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.PAY_ORDER);
        urlParse.putValue("phone", SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY))
                .putValue("pay_type", "app")
                .putValue("goods_name", "开通超级VIP")
                .putValue("vip_time", selectVipBean.vip_time);

        if (BuildConfig.DEBUG) {
            urlParse.putValue("money", "0.01");
        } else {
            urlParse.putValue("money", selectVipBean.cost_price);
        }

        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<WXPayBean>() {

                    @Override
                    protected void onCommon() {
                        super.onCommon();

                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(WXPayBean wxPayBean) {
                        if (wxPayBean != null) {
                            PayReq req = new PayReq();
                            req.appId = wxPayBean.appid;
                            req.partnerId = wxPayBean.partnerid;
                            req.prepayId = wxPayBean.prepayid;
                            req.nonceStr = wxPayBean.noncestr;
                            req.timeStamp = wxPayBean.timestamp + "";
                            req.packageValue = wxPayBean.packageName;
                            req.sign = wxPayBean.sign;
                            req.extData = "app data"; // optional

                            Log.i(TAG, "out_trade_no=" + wxPayBean.out_trade_no);
                            SharedPreferencesUtils.setStringDate(Constants.OUT_TRADE_NO_SHAREPREFERS_KEY, wxPayBean.out_trade_no);
                            WXPayEntryActivity.type = 1;

                            boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
                            if (isChildControl) {
                                setAllowBack(true);
                                Intent intent = new Intent(OpenVipSpendActivity.this, DialRTAService.class);
                                intent.putExtra("rtaType", 4);
                                intent.putExtra("allowPackName", Constants.ALLOW_WECHAT_PACK_NAME);
                                startService(intent);
                            }

                            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                            api.sendReq(req);
                        } else {
                            showToast("返回数据为空");
                        }
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == 100) {
            getData();
        }
    }

    //根据type跳转不同界面
    private void bannerJump(AppDialogBean appDialogBean) {
        switch (appDialogBean.type) {
            case 0://跳转H5
                Intent intent2 = new Intent(this, AdvertWebActivity.class);
                intent2.putExtra("title", appDialogBean.name);
                intent2.putExtra("url", appDialogBean.url);
                startActivityAllow(intent2);
                break;
            case 2://跳转视频页面
                Intent intent = new Intent(this, SpecialTopicVideoActivity.class);
                intent.putExtra("isOnlyPlay", true);
                intent.putExtra("video_title", appDialogBean.name);
                intent.putExtra("video_url", appDialogBean.url);
                startActivityAllow(intent);
                break;
            case 4:
                UmengEventUtil.onEvent(babyApplication, "vip_101_download_click_id", appDialogBean.android_name);
                SystemUtils.openAppMarket(this, appDialogBean.android_name);
                break;
            default:
                break;
        }
    }
}
